package com.yvon.core;

import com.yvon.core.page.ListData;
import com.yvon.core.page.SearchCriteria;
import com.yvon.core.result.CommonResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

public abstract class BaseCrudController<E, D, V, S extends IBaseService<E>> extends AbstractController<E, D, V> {
    @Autowired
    private S baseService;

    public BaseCrudController() {

        Class c = getEntityClass();

    }

    @PostMapping
    @ApiOperation(
        value = "新增",
        notes = "新增API"
    )
    public CommonResult<D> add(@RequestBody V vo) {

        E entity = this.voToEntity(vo);
        this.baseService.save(entity);
        return this.success(this.entityToDto(entity));
    }

    @PutMapping
    @ApiOperation(
        value = "更新",
        notes = "更新API"
    )
    public CommonResult<D> update(@RequestBody V vo) {
        E entity = this.voToEntity(vo);
        this.baseService.updateById(entity);
        return this.success(this.entityToDto(entity));
    }

    @DeleteMapping
    @ApiOperation(
        value = "删除",
        notes = "删除API"
    )
    public CommonResult deleteByIds(@RequestBody List<String> ids) {
        return this.result(this.baseService.removeByIds(ids));
    }

    @GetMapping({"/id/{id}"})
    @ApiOperation(
        value = "根据编号查询信息",
        notes = "根据编号查询信息API"
    )
    public CommonResult<D> getById(@PathVariable("id") String id) {
        E entity = this.baseService.getById(id);
        return this.success(this.entityToDto(entity));
    }

    @PostMapping({"list"})
    @ApiOperation(
        value = "分页查询",
        response = ListData.class,
        notes = "分页查询API  <br />  1.可使用参数:  <br />    xxx        -> xxx  <br />"
    )
    public CommonResult<ListData<D>> findList(@RequestBody SearchCriteria searchCriteria) {
        ListData listData = this.baseService.page(searchCriteria);
        listData.setList(this.entityToDto(listData.getList()));
        return CommonResult.success(listData);
    }

    protected S getService() {
        return this.baseService;
    }

}
